import axios from 'axios'
import serviceConfig from './config'
import qs from 'qs'
import router from '@/router'

// Add a response interceptor
axios.interceptors.response.use(function (response) { // 响应拦截
                                                      // Do something with response data
  return response.data
}, function (error) {
  // Do something with response error
  return Promise.reject(error.response)
})

export default {
  request: function (api, params, headers) {
    if (api.mock && api.mock.enable === true) { // 模拟响应数据
      console.log('mock data: [app=' + api.app + ', path=' + api.path + ']')
      return Promise.resolve(api.mock.data)
    }
    const app = serviceConfig[api.app || 'yunji'] // 获取api对应的app配置
    const config = {
      baseURL: app.baseUrl,
      url: api.path,
      method: api.method || 'POST', // 请求方法
      timeout: api.timeout || 0, // 0 默认不设置超时
      withCredentials: true, // 跨域时是否进行请求头认证
      responseType: api.dataType || 'text', // 响应数据格式
      validateStatus: function (status) { // 校验响应状态，用来区分是请求成功还是失败
        return status < 400
      },
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': api.contentType || 'application/x-www-form-urlencoded',
        'Accept': '*/*'
      }
    }
    if (headers) {
      Object.keys(headers).forEach((key) => {
        config.headers[key] = headers[key]
      })
    }

    if (config.method.toUpperCase() === 'GET') {
      config.params = params
    } else {
      config.data = params
      config.transformRequest = [function (data) { // 如果是post请求，且请求内容格式是application/json,则对请求体数据格式化
        return qs.stringify(data)
      }]
    }
    let $http = axios(config)
    return $http
  }
}
